package pageShare

import (
	"context"
	"encoding/json"
	"errors"

	"laundry-service/app/client/internal/svc"
	"laundry-service/app/client/internal/types"
	"laundry-service/entity"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreatePageShareLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreatePageShareLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePageShareLogic {
	return &CreatePageShareLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreatePageShareLogic) CreatePageShare(req *types.CreatePageShareRequest) (resp *types.CreatePageShareReply, err error) {
	userId, _ := l.ctx.Value("userId").(json.Number).Int64()
	_, err = l.svcCtx.Db.GetAdminById(int(userId))
	if err != nil {
		return nil, err
	}

	_, err = l.svcCtx.Db.GetPageShareByPath(req.Path)
	if err == nil {
		return nil, errors.New("path already exists")
	}

	newPageShare := &entity.PageShare{
		Path:        req.Path,
		Title:       req.Title,
		Description: req.Description,
		ImageUrl:    req.ImageUrl,
	}

	err = l.svcCtx.Db.SavePageShare(newPageShare)
	if err != nil {
		l.Logger.Errorf("create page share error: %v", err)
		return nil, err
	}

	pageShare, err := l.svcCtx.Db.GetPageShareByPath(newPageShare.Path)
	if err != nil {
		l.Logger.Errorf("get page share by id error: %v", err)
		return nil, err
	}

	return &types.CreatePageShareReply{
		Id:          pageShare.ID,
		CreatedAt:   pageShare.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt:   pageShare.UpdatedAt.Format("2006-01-02 15:04:05"),
		Path:        pageShare.Path,
		Title:       pageShare.Title,
		Description: pageShare.Description,
		ImageUrl:    pageShare.ImageUrl,
	}, nil
}
